package com.imooc.mvcdemo.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;

import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

public class RealTimeLog {

    /**
     * @param args
     */
    public static void main(String[] args) {
        try {
            // 请求URI可以拼接一些要求。详见API接口http://sae.sina.com.cn/doc/api.html#id3
            getLog("/log/http/2015-07-21/1-access.log");
            System.out.println("======================");
            getLog("/log/http/2015-07-21/2-access.log");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static List<String> getLog(String uri) {
        List<String> contents = new ArrayList<String>();
        InputStream instream = null;
        HttpClient client = null;
        try {
            Properties prop = new Properties();// 属性集合对象
            InputStream fis;

            String fileName = "/" + "jdbc.properties";
            fis = RealTimeLog.class.getResourceAsStream(fileName);
            prop.load(fis);// 将属性文件流装载到Properties对象中

            String accesskey = prop.getProperty("username");
            String secretkey = prop.getProperty("password");

            String url = "http://g.sae.sina.com.cn" + uri;
            String encoding = "utf-8";
            client = new DefaultHttpClient();
            // 获取请求触发时间，SAE接口中的时间是秒，JAVA getTime()方法得到的是毫秒，所以除1000
            String time = new Date().getTime() / 1000 + "";
            System.out.println(time);
            // String headinfo[] = {"x-sae-timestamp:"+time, "x-sae-accesskey:"+accesskey};

            // 签名基础参数拼接，冒泡排序，就是大的在后面，反正参数少，就写死吧。记得都要小写。GET大写
            String authtemp = "GET\n" + uri + "\n" + "x-sae-accesskey:" + accesskey.toLowerCase()
                    + "\nx-sae-timestamp:" + time;// 使用HMACSHA256加密，密钥为SECRETKEY，应用的。应用设置里可见
            Mac mac = Mac.getInstance("HmacSHA256");
            byte[] secretByte = secretkey.getBytes("UTF-8");
            byte[] dataByte = authtemp.getBytes("UTF-8");
            SecretKey secret = new SecretKeySpec(secretByte, "HmacSHA256");
            mac.init(secret);
            byte[] finalinfo = mac.doFinal(dataByte);
            // 得到加密二进制

            // 然后用BASE64编码成字符串，前面拼接SAEV1_HMAC_SHA256 ，务必不要漏了中间的空格
            String auth = "SAEV1_HMAC_SHA256 " + Base64.encodeBase64String(finalinfo);
            System.out.println("auth: " + auth);
            HttpGet get = new HttpGet(url); // 添加请求HEADER
            get.setHeader("Host", "g.sae.sina.com.cn");
            get.setHeader("Accept", "text/plain");
            get.setHeader("x-sae-accesskey", accesskey);
            get.setHeader("x-sae-timestamp", time);
            get.setHeader("Authorization", auth);

            // 得到返回的response.
            HttpResponse response = client.execute(get);
            // 得到返回的client里面的实体对象信息.
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                System.out.println("内容编码是：" + entity.getContentEncoding());
                System.out.println("内容类型是：" + entity.getContentType());
                // 得到返回的主体内容.
                instream = entity.getContent();
                BufferedReader reader = new BufferedReader(new InputStreamReader(instream, encoding));
                String line = reader.readLine();
                while (line != null) {
                    // 显示请求结果 System.out.println(response.toString());
                    System.out.println(line);
                    contents.add(line);
                    line = reader.readLine();
                }

            }

        } catch (Exception e1) {
            e1.printStackTrace();
        }// 属性文件流
        finally {
            try {
                instream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            // 关闭连接.
            client.getConnectionManager().shutdown();
        }
        return contents;
    }

}